package com.example.gatewayservice.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator gatewayRouters(RouteLocatorBuilder builder){
        return builder.routes()
                .route(r -> r.path("/student/**")
                        .filters(f -> f.addRequestHeader("first-request","first-request-header").addResponseHeader("first-response","first-response-header"))
                        .uri("http://localhost:8083/"))
                .build();
    }

    @Bean
    public GlobalFilter globalFilter(){
        return new GlobalFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
                builder.header("request-global_filter","This is request global filter value").build();
                return chain.filter(exchange).then(Mono.fromRunnable(() ->{
                    String uri = exchange.getRequest().getURI().toString();
                    System.err.println(uri);
                }));
            }
        };
    }
}
